<?php
class CmsFieldGroupControl extends BaseViewControl
{
    protected $title;
    protected $item;
    protected $fields;

    public function GetConfig()
    {
        return CmsConfig::GetInstance();
    }

    public function CmsFieldGroupControl($title, $view, $fields, $item)
    {
        $this->title = $title;
        parent::__construct(String::ToUrlFriendly($this->title));
        $this->view = $view;
        $this->fields = $fields;
        $this->item = $item;
        $this->config->AddSharedJs('CmsFieldGroupControl');
    }

    public function Render()
    {
        $field_positions = $this->GetFieldPositions($left_fields, $right_fields);
        $callback = array($this, 'FormatColumn');

        $this->Replace('title', $this->title);
        $this->Replace('model_name', $this->view->GetModelName());
        $this->Repeat('field_position', $field_positions);
        $this->Repeat('left_field', $left_fields, $callback);
        $this->Repeat('right_field', $right_fields, $callback);
        $this->Replace($this->item);
        return parent::Render();
    }

    public function FormatColumn($item)
    {
        $item = parent::FormatColumn($item);
        $item['caption_style'] = count($this->fields) == 1 ? 'display:none' : null;
        return $item;
    }

    protected function GetFieldPositions(&$left, &$right)
    {
        $fields = $this->fields;
        $count = count($fields);
        if ($count == 1)
        {
            $left = array_slice($fields, 0, 1);
            $right = array_slice($fields, 1, $count);
            return array(
                array('field_position'=>'left')
            );
        }
        else
        {
            $offset = ceil($count/2);
            $left = array_slice($fields, 0, $offset);
            $right = array_slice($fields, $offset, $count);
            return array(
                array('field_position'=>'left'),
                array('field_position'=>'right')
            );
        }
    }
}
?>
